<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
require_once ('./application/controllers/authenticate.php');

class Comment extends Authenticate {

    const COMMENT_PER_PAGE = 15;
    const COMMENT_PAGE_RANGE = 5;

    public $_rpps = array(10, 15, 20, 25, 30, 45, 100, 200);

    public $_bas = array(
        'Chấp nhận' => 'admin/cms/comment/bulk_action/approved/',
        'Từ chối' => 'admin/cms/comment/bulk_action/disapproved/'
    );

    function __construct() {
        global $active_article_function;
        $active_article_function = 'admin/cms/comment/index';
        parent::__construct();
        $this->load->model('admin_model');
        $this->load->model('cms_comment_model');
    }

    protected function _eventLoadLayout() {
        $this->page['title'] = 'Quản lý bình luận';
        $this->module['title'] = 'Quản lý bình luận';
    }

    public function index() {
        try {
            $this->filtered_list('index');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    protected function _initListData($return_url, $is_approved = null, $title = null) {
        $filters = $this->input->post('filters');
        $current_page = intval($this->input->post('current_page'));
        $record_per_page = intval($this->input->post('record_per_page'));
        if ($record_per_page == 0) {
            $record_per_page = self::COMMENT_PER_PAGE;
        }
        $conds = null;
        $filters['is_approved']['type'] = 'equal';
        if (!is_integer($is_approved)) {
            $filters['is_approved']['value'] = '';
        } else {
            $filters['is_approved']['value'] = intval($is_approved);
        }
        // Init Filters
        if (!isset($filters['id'])) {
            $filters['id']['value'] = "";
            $filters['id']['type'] = 'equal';
        }
        if (!isset($filters['title'])) {
            $filters['title']['type'] = 'text';
            $filters['title']['value'] = null;
        }
        if (!isset($filters['email'])) {
            $filters['email']['type'] = 'text';
            $filters['email']['value'] = null;
        }
        if ($filters) {
            $conds = analyze_filters($filters);
        }

        if (empty($filters['created_at_from'])) {
            $filters['created_at_from'] = null;
        } else {
            $created_at_from = get_time_stamp($filters['created_at_from']);
            $conds['created_at_from'] = 'created_at >= ' . $created_at_from;
        }
        if (empty($filters['created_at_to'])) {
            $filters['created_at_to'] = null;
        } else {
            $created_at_to = get_time_stamp($filters['created_at_to']);
            if (isset($created_at_from)) {
                if ($created_at_from >= $created_at_to) {
                    $conds['created_at_from'] = 'created_at >= ' . $created_at_to;
                    $filters['created_at_from'] = date('d/m/Y', $created_at_to);
                }
            }
            $conds['created_at_to'] = 'created_at <= ' . get_time_stamp($filters['created_at_to'], true);
        }

        if (empty($filters['approved_at_from'])) {
            $filters['approved_at_from'] = null;
        } else {
            $approved_at_from = get_time_stamp($filters['approved_at_from']);
            $conds['approved_at_from'] = 'approved_at >= ' . $approved_at_from;
        }
        if (empty($filters['approved_at_to'])) {
            $filters['approved_at_to'] = null;
        } else {
            $approved_at_to = get_time_stamp($filters['approved_at_to']);
            if (isset($approved_at_from)) {
                if ($approved_at_from >= $approved_at_to) {
                    $conds['approved_at_from'] = 'approved_at >= ' . $approved_at_to;
                    $filters['approved_at_from'] = date('d/m/Y', $approved_at_to);
                }
            }
            $conds['approved_at_to'] = 'approved_at <= ' . get_time_stamp($filters['approved_at_to'], true);
        }

        if (count($conds) == 0) {
            $query = 'SELECT COUNT(id) as count_result FROM cms_comment LIMIT 0, 1';
        } else {
            $query = 'SELECT COUNT(id) as count_result FROM cms_comment WHERE ' . implode(' AND ', $conds) . ' LIMIT 0, 1';
        }

        // Get Count Comments
        $rs = $this->cms_comment_model->db->query($query);
        $count_results = $rs->row()->count_result;
        $rs->free_result();

        // Paginate
        if ($current_page <= 1) {
            $current_page = 1;
        }
        $start = ($current_page - 1) * $record_per_page;
        if ($start <= 0) {
            $start = 0;
        }
        $total_pages = ceil($count_results / $record_per_page);
        $delta = ceil(self::COMMENT_PAGE_RANGE / 2);
        if ($current_page - $delta > $total_pages - self::COMMENT_PAGE_RANGE) {
            $pag['lower'] = $total_pages - self::COMMENT_PAGE_RANGE;
            $pag['upper'] = $total_pages;
        } else {
            if ($current_page - $delta < 0) {
                $delta = $current_page;
            }
            $offset = $current_page - $delta;
            $pag['lower'] = $offset + 1;
            $pag['upper'] = $offset + self::COMMENT_PAGE_RANGE;
        }
        if ($pag['lower'] <= 1) {
            $pag['lower'] = 1;
        }
        if ($pag['upper'] >= $total_pages) {
            $pag['upper'] = $total_pages;
        }
        $pag['total'] = $total_pages;

        // Transfer Variables
        $data['module_title'] = $title;
        $data['return_url'] = $return_url;
        $data['record_per_page'] = $record_per_page;
        $data['rpps'] = $this->_rpps;
        foreach ($this->_bas as $action_label => $url) {
            $this->_bas[$action_label] = $url . 'return/' . $return_url;
        }
        $data['bas'] = $this->_bas;
        $data['count_total'] = $count_results;
        $data['current_page'] = $current_page;
        $data['paginator'] = $pag;
        $data['filters'] = $filters;
        $data['collection'] = $this->cms_comment_model->get_collection($start, $record_per_page, $conds, 'created_at DESC, id DESC');
        $data['save_action'] = site_url('admin/cms/comment/save', true);
        return $data;
    }

    public function filtered_list($alias) {
        try {
            global $active_comment_article;
            $ajax_action = $this->input->getParam('ajax_action');
            $active_comment_article = 'admin/cms/comment/index';
            $data = $this->_initListData($alias);
            $data['form_action'] = site_url($active_comment_article, true);
            if (empty($ajax_action)) {
                $this->setPageContent('admin/cms/comment/list', $data);
                $this->renderLayout('layouts/fullcolumn');
            } else {
                $this->setPageContent('admin/cms/comment/ajax/list', $data);
                $this->renderLayout('layouts/ajax');
            }
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    function save() {
        try {
            $id = $this->input->post('id');
            $data = $this->input->post('data');
            $go_back = $this->input->post('go_back');
            $user_id = $this->admin_model->get_id();
            $updated_time = time();

            // Add new Comment
            if (empty($id)) {
                $data['user_id'] = $user_id;
                $data['created_at'] = $updated_time;
                // Add To Temporary Comments
                if (empty($data['is_approved'])) {
                    $data['is_approved'] = 2;
                }
                $id = $this->cms_comment_model->add_comment($data);
                $this->st_registry->register('admin/cms/comment/success', 'Thêm bình luận mới thành công');
            } else {
                // Update Comment
                $this->cms_comment_model->update_comment($id, $data);
                $this->st_registry->register('admin/cms/comment/success', 'Lưu thông tin bình luận ['.$data['title'].'] thành công');
            }            
        } catch (Exception $ex) {
            $this->st_registry->register('admin/cms/comment/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
        if (empty($go_back)) {
            redirect(site_url('admin/cms/comment/edit/id/'.$id, true));
        } else {
            redirect(site_url('admin/cms/comment/index', true));
        }
    }

    public function edit() {
        try {
            global $active_comment_article;
            $active_comment_article = 'admin/cms/comment/index';
            $id = $this->input->getParam('id');
            if ($id) {
                $data['comment'] = $this->cms_comment_model->load_by_id($id);
                if (!$data['comment']) {
                    redirect(site_url('admin/cms/comment/index', true));
                    return;
                }
            } else {
                $data['comment'] = new stdClass();
            }
            $data['return_url'] = site_url('admin/cms/comment/index', true);
            $this->setPageContent('admin/cms/comment/edit', $data);
            $this->renderLayout('layouts/fullcolumn');
        } catch (Exception $ex) {
            $this->st_registry->register('admin/cms/comment/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
    }

    private function is_ajax_request() {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            return true;
        }
        $ajax_action = $this->input->getParam('ajax_action');
        if (!empty($ajax_action)) {
            return true;
        }
        return false;
    }

    public function delete() {
        $return_url = $this->input->getParam('return');
        $ajax_action = $this->is_ajax_request();
        $id = $this->input->getParam('id');
        if (empty($id)) {
            $this->st_registry->register('admin/cms/comment/error', 'Không xác định được bình luận cần xóa (ID)?');
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/comment/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/comment/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/comment/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/comment/filtered_list/' . $return_url, true));
                }
            }
            exit();
        }
        $this->cms_comment_model->delete_comment($id);
        $this->st_registry->register('admin/cms/comment/success', 'Xóa bình luận thành công');
        if (!empty($ajax_action)) {
            redirect(site_url('admin/cms/comment/filtered_list/' . $return_url . '/ajax_action/true', true));
        } else {
            redirect(site_url('admin/cms/comment/filtered_list/' . $return_url, true));
        }
    }

    public function approved() {
        try {
            $return_url = $this->input->getParam('return');
            $ajax_action = $this->is_ajax_request();
            $id = $this->input->getParam('id');
            if (empty($id)) {
                $this->st_registry->register('admin/cms/comment/error', 'Không xác định được bình luận cần duyệt (ID)?');
                if (empty($return_url)) {
                    if (!empty($ajax_action)) {
                        redirect(site_url('admin/cms/comment/index/ajax_action/true', true));
                    } else {
                        redirect(site_url('admin/cms/comment/index', true));
                    }
                } else {
                    if (!empty($ajax_action)) {
                        redirect(site_url('admin/cms/comment/filtered_list/' . $return_url . '/ajax_action/true', true));
                    } else {
                        redirect(site_url('admin/cms/comment/filtered_list/' . $return_url, true));
                    }
                }
                exit();
            }
            $this->cms_comment_model->update_comment($id, array('is_approved' => 1));
            $this->st_registry->register('admin/cms/comment/success', 'Bình luận đã được duyệt');
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/comment/filtered_list/' . $return_url . '/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/comment/filtered_list/' . $return_url, true));
            }
        } catch (Exception $ex) {
            $this->st_registry->register('admin/cms/comment/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
    }

    public function disapproved() {
        try {
            $return_url = $this->input->getParam('return');
            $ajax_action = $this->is_ajax_request();
            $id = $this->input->getParam('id');
            if (empty($id)) {
                $this->st_registry->register('admin/cms/comment/error', 'Không xác định được bình luận cần hủy duyệt (ID)?');
                if (empty($return_url)) {
                    if (!empty($ajax_action)) {
                        redirect(site_url('admin/cms/comment/index/ajax_action/true', true));
                    } else {
                        redirect(site_url('admin/cms/comment/index', true));
                    }
                } else {
                    if (!empty($ajax_action)) {
                        redirect(site_url('admin/cms/comment/filtered_list/' . $return_url . '/ajax_action/true', true));
                    } else {
                        redirect(site_url('admin/cms/comment/filtered_list/' . $return_url, true));
                    }
                }
                exit();
            }
            $this->cms_comment_model->update_comment($id, array('is_approved' => 2));
            $this->st_registry->register('admin/cms/comment/success', 'Hủy duyệt bình luận');
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/comment/filtered_list/' . $return_url . '/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/comment/filtered_list/' . $return_url, true));
            }
        } catch (Exception $ex) {
            $this->st_registry->register('admin/cms/comment/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
    }

    public function bulk_action($alias) {
        $data_type = $this->cms_comment_model->parse_alias($alias);
        $return_url = $this->input->getParam('return');
        $ajax_action = $this->input->getParam('ajax_action');
        $ids = $this->input->getParam('selected');
        if (!is_array($ids) && empty($ids)) {
            $this->st_registry->register('admin/cms/comment/error', 'Hãy chọn ít nhất một bình luận để ' . $data_type['label']);
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/comment/index/' . $return_url . '/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/comment/index/' . $return_url, true));
            }
            return;
        }
        $count = count($ids);
        foreach ($ids as $id) {
            $this->cms_comment_model->update_comment($id, array('is_approved' => $data_type['status']));
        }
        $this->st_registry->register('admin/cms/comment/success', 'Thiết lập trạng thái ' . $data_type['label'] . ' (' . $count . ') bình luận thành công');
        if (!empty($ajax_action)) {
            redirect(site_url('admin/cms/comment/index/' . $return_url . '/ajax_action/true', true));
        } else {
            redirect(site_url('admin/cms/comment/index/' . $return_url, true));
        }
    }

    public function view_logs() {
        $id = intval(trim($this->input->post('id')));
        if (empty($id)) {
            echo 'Hệ thống không tìm thấy nhật ký sửa đổi của bình luận';
            exit();
        }
        $data['logs'] = $this->cms_comment_model->get_logs($id);
        $this->setPageContent('admin/cms/comment/ajax/logs', $data);
        $this->renderLayout('layouts/ajax');
    }
}